//渲染本章分类的最新分类
axios.get('http://api-breakingnews-web.itheima.net/my/article/cates', {
    headers: {
        Authorization: localStorage.getItem('token')
    }
}).then(function (test) {

    const {data, message, status} = test.data
    if (status === 0) {
        data.forEach(function (item) {

            let option = `<option value="${item.Id}" lay-verify="cate">${item.name}</option>`
            $('select[name=category]').append(option)
            layui.form.render('select', 'category');
        })

    }

})


//获取个人发布于草稿文章信息并渲染到页面
//先定义要传的数据
const query = {
    pagenum: 1,
    pagesize: 2,
    cate_id: '',
    state: '',
}

let total = 0
function getlist() {
    axios.get('http://api-breakingnews-web.itheima.net/my/article/list', {
        headers: {
            Authorization: localStorage.getItem('token')
        },
        params: query,
    }).then(function (test) {
        console.log(test)
        $('tbody').empty()
        let {data, message, status} = test.data
        if (status === 0) {
            data.forEach(function (obj, index) {
                let theTr = `<tr>
        <td>${obj.title}</td>
        <td>${obj.cate_name}</td>
        <td>${obj.pub_date}</td>
        <td>${obj.state}</td>
        <th>
        <button myid="${obj.Id}" type="button" class="layui-btn layui-btn-xs layui-btn-danger del">删除</button>
            </th>
    </tr>`
                $('tbody').append(theTr)
            })
        }
        total = test.data.total
        getpage()
    })
}

getlist()


//根据条件筛选显示
$('form').on('submit', function (e) {
    e.preventDefault()
    query.cate_id = $('select[name=category]').val()
    query.state = $('select[name=state]').val()
    getlist()
})

//删除事件
$('tbody').on('click', '.del', function () {
    let id = $(this).attr('myid')
    axios.get(`http://api-breakingnews-web.itheima.net/my/article/delete/${id}`, {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(function (test) {
        if (test.data.status === 0) {
            layer.msg(test.data.message)
            getlist()
        }
    })
})


//显示分页空间,因要配合返回的数据进行渲染,所以在有返回数据后根据数据渲染
function getpage() {
    layui.use('laypage', function () {
        var laypage = layui.laypage;

        //执行一个laypage实例
        laypage.render({
            elem: 'page'
            , count: total
            , curr: query.pagenum
            , limit: query.pagesize
            , layout: ['count', 'prev', 'page', 'next', 'limit']
            , limits: [2, 3, 5, 8]
            , jump: function(obj, first){
                //obj包含了当前分页的所有参数，比如：
                //console.log(obj.curr);    得到当前页，以便向服务端请求对应页的数据。
                //console.log(obj.limit);   得到每页显示的条数

                //首次不执行
                if(!first){
                    query.pagesize = obj.limit
                    query.pagenum = obj.curr
                    getlist()
                }
            }
        });
    });
}